package com.huajx.tuopuda.server.udp;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.ServerSocket;

/**
 * @program: di-parent
 * @description:
 * @author: lisa 叶新华
 * @create: 2019-09-25 09:40
 */
public class TuopudaUdpServer extends Thread{
    private ServerSocket server;
    private BufferedReader reader;
    private JTextArea jt = new JTextArea(15,20);
    private JTextField jf = new JTextField();
    private String word;
    private byte[] buf ;
    private int port = 60000;
    private MulticastSocket socket = null;
    private InetAddress iaddress = null;

    public TuopudaUdpServer(){
        init();

        jf.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                word = jf.getText();
                buf = word.getBytes();
                try {
                    iaddress = InetAddress.getLocalHost();
                    socket = new MulticastSocket(port);
                    socket.setTimeToLive(1);
                    socket.joinGroup(iaddress);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                jt.append("考勤数据开始发送数据！！！\n");
                start();
            }
        });
    }

    public void init(){
        JFrame frame = new JFrame("翼校云平安学子门禁考勤服务站");
        JScrollPane js = new JScrollPane(jt);
        Container con = frame.getContentPane();
        frame.setLocationRelativeTo(null);
        con.add(js,"North");
        con.add(jf,"South");

        frame.setSize(800,600);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    public void run(){
        while(true){
            buf = word.getBytes();
            DatagramPacket packet = new DatagramPacket(buf, buf.length,iaddress,port);
            jt.append(word + "\n");
            try {
                socket.send(packet);
                sleep(3000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args){
        TuopudaUdpServer sS = new TuopudaUdpServer();
    }
}
